﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Data;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class ReadXML : MissionPlugin
    {
        [Package(Direction.Input, "Defines the xml file, you like to read.")]
        enum XMLFiles
        {
            [Column(typeof(string), "The xml file you like to read?")]
            XmlFilePath
        }

        [Package(Direction.Output, "Defines the data, which was load from the given xml-files.")]
        enum Data { }

        [Plugin(PluginDevStatus.Production, "Reads the given xml-files into the package.")]
        public ReadXML()
        {
        }

        public override void Initialize()
        {

            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }

        /// <summary>
        /// Generate new Source-content.
        /// </summary>
        protected override void Work()
        {
            DataTableReader xmlFiles = this.GetDataReader(typeof(XMLFiles));
            while (xmlFiles.Read())
            {
                this.AddNewLoggingMessage(typeof(XMLFiles), String.Format("read: {0}", xmlFiles[XMLFiles.XmlFilePath.ToString()].ToString()));

                XmlDocument document = new XmlDocument();
                document.Load(xmlFiles[XMLFiles.XmlFilePath.ToString()].ToString());

                XmlNode root = document.GetElementsByTagName("NewDataSet").Item(0);
                XmlNodeList tableRows = root.ChildNodes;

                // create columns
                List<KeyValuePair<string, Type>> columnDefinitions = new List<KeyValuePair<string, Type>>();
                foreach (XmlNode nodeOn in tableRows.Item(0).ChildNodes)
                {
                    columnDefinitions.Add(new KeyValuePair<string, Type>(nodeOn.Name, typeof(string)));
                }
                this.CreateNewSchemaForPackage(typeof(Data), columnDefinitions);

                // add rows
                foreach (XmlNode rowNodeOn in tableRows)
                {
                    DataRow newRow = this.CreateNewRowFromPackage(typeof(Data));
                    foreach (XmlNode columnNodeOn in rowNodeOn.ChildNodes)
                    {
                        newRow[columnNodeOn.Name] = columnNodeOn.InnerText;
                    }
                    this.AddNewRowToPackage(typeof(Data), newRow);
                }
            }
        }
    }
}
